package com.heima.behavio.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavio.mapper.BhReadMapper;
import com.heima.behavio.service.BhReadService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ReadDto;
import com.heima.model.behavior.pojos.BhRead;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BhReadServiceImpl extends ServiceImpl<BhReadMapper, BhRead> implements BhReadService {

    @Autowired
    private BhReadMapper bhReadMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult readCount(ReadDto dto) {
        ApUser apUser = ApThreadLocalUtil.getUser();
        String key = dto.getArticleId()+"_"+apUser.getId()+"_readCount";
        String value = cacheService.get(key);
        if(value!=null&&""!=value){
            BhRead bhRead= JSON.parseObject(value,BhRead.class);
            bhRead.setCount(bhRead.getCount()+1);
            bhReadMapper.updateById(bhRead);
            cacheService.set(key,JSON.toJSONString(bhRead));
            return ResponseResult.okResult(bhRead);
        }else{
            BhRead bhRead = new BhRead();
            BeanUtils.copyProperties(dto,bhRead);
            bhRead.setUserId(apUser.getId());
            LambdaQueryWrapper<BhRead> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BhRead::getArticleId,dto.getArticleId());
            wrapper.eq(BhRead::getUserId,apUser.getId());
            BhRead bhRead1 = bhReadMapper.selectOne(wrapper);
            if(null == bhRead1){
                bhReadMapper.insert(bhRead);
                cacheService.set(key,JSON.toJSONString(bhRead));
                return ResponseResult.okResult(bhRead);
            }
            bhRead.setCount(bhRead1.getCount()+1);
            bhRead.setId(bhRead1.getId());
            bhReadMapper.updateById(bhRead);
            cacheService.set(key,JSON.toJSONString(bhRead));
            return ResponseResult.okResult(bhRead);
        }
    }
}
